package com.terra;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
//import com.google.android.maps.OverlayItem;
import com.lamerman.FileDialog;

public class terraDroid extends MapActivity {
	
	int nIndex = 0;
	
	//MapItemizedOverlay itemizedoverlay;
	List<Overlay> mapOverlays;
    ImageButton buttonToggleCentering;
    Spinner  spinnerMapType;
    ArrayAdapter<String> adapterMap; 
    MyCacheHandler myCaches;
    ImportTC importME;
    
//	public static final int REQUEST_SAVE = 1;
//	public static final int REQUEST_LOAD = 2;
	public static final int REQUEST_LOAD_GPX = 1;
	public static final int REQUEST_LOAD_TEMP = 2;
	public static final int REQUEST_SAVE_TEMP = 3;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Globals.myContext = this;

        spinnerMapType= (Spinner) findViewById(R.id.spinnerMapType);
        String myGroups[] = new String[2];
        myGroups[0] = "Street View";
        myGroups[1] = "Satellite";
        
        adapterMap = new ArrayAdapter<String>(this, R.layout.myspinnerlayout, myGroups);
        adapterMap.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerMapType.setAdapter(adapterMap);
        
        spinnerMapType.setSelection(0);
        
        spinnerMapType.setOnItemSelectedListener(new MySpinnerListener());

        //Globals.drawablePin =  = getResources().getDrawable(R.drawable.pin);
        
        Globals.mapView = (MapView) findViewById(R.id.mapview);
        Globals.mapView.setBuiltInZoomControls(true);
        Globals.mapView.setLongClickable(true);
       
        Globals.myLocationOverlay = new MyLocationOverlay(this, Globals.mapView);
        Globals.myLocationOverlay.enableCompass(); // compass is displayed
        Globals.myLocationOverlay.enableMyLocation(); // blue circle is displayed correctly 
       
        Globals.drawableRedPin = getResources().getDrawable(R.drawable.redpin);
        
        mapOverlays = Globals.mapView.getOverlays();
        mapOverlays.add(Globals.myLocationOverlay);
        
        buttonToggleCentering = (ImageButton) findViewById(R.id.imageButton1);
        buttonToggleCentering.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	Globals.bTrackGPS = !Globals.bTrackGPS;
            	if( Globals.bTrackGPS ) {
            		buttonToggleCentering.setAlpha(255);
                   Globals.myLocationOverlay.enableMyLocation(); // blue circle is displayed correctly 
            	}
            	else {
            		buttonToggleCentering.setAlpha(96);
            		Globals.myLocationOverlay.disableMyLocation();
            	}
            	
            	//Log.d("Debug", "Centering "+Globals.bTrackGPS);
            }
          });
    }

    @Override
	protected void onResume() {
        super.onResume();
        
        // just return if last run crashed
        if( Globals.GetReset() )
        	return;
        
    	Globals.OnResume();

    	if( Globals.bLoadLastFile && Globals.strLastFile!="" )
    		loadGPX(Globals.strLastFile);
    	
    	//LoadTempCaches();
    	
    	// set reset flag in case of crash
    	Globals.Reset();
    }

    @Override
	protected void onPause() {
        super.onPause();
        Log.d("Debug", "On pause");
    	Globals.OnPause();
    }
    
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
    public void SetSpan(double dLat, double dLon) {
    	int ndLat = (int) (dLat * 1e6);
    	int ndLon = (int) (dLon * 1e6);
    	
    	Globals.mapView.getController().zoomToSpan(ndLat, ndLon);
    }
    
    public void SetCenter(double dLat, double dLon) {
    	int nLat = (int) (dLat * 1e6);
    	int nLon = (int) (dLon * 1e6);
    	GeoPoint gp = new GeoPoint(nLat, nLon);
    	Globals.mapView.getController().setCenter(gp);
    }
    
    public void SetRange(double dLat1, double dLon1, double dLat2, double dLon2) {
    	double dCenterLat = dLat1 + (dLat2-dLat1)/2;
    	double dCenterLon = dLon1 + (dLon2-dLon1)/2;
    	SetCenter(dCenterLat, dCenterLon);
    	SetSpan((dLat2-dLat1), (dLon2-dLon1));
    	
    	Globals.dGPSLat = dCenterLat;
    	Globals.dGPSLon = dCenterLon;
    }

	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mainmenu, menu);
        return true;
    }
       
	// This method is called once the menu is selected
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
			
		case R.id.item1:
			//importME = new ImportTC();
			Toast toast = Toast.makeText(this, "Sorry, waiting for TC 3.0", Toast.LENGTH_LONG);
			toast.show();
			break;
			
		case R.id.settings:
			Log.d("Debug", "Creating settings intent");
            Intent settingsActivity = new Intent(getBaseContext(), Preferences.class);
            startActivity(settingsActivity);

			break;
			
		case R.id.about:
			AboutDialog myAboutBox = new AboutDialog(this);
			myAboutBox.show();
			break;
			
		case R.id.loadgpx:
    		Intent fileIntent = new Intent(terraDroid.this, FileDialog.class);
			fileIntent.putExtra(FileDialog.START_PATH, "/sdcard");
			fileIntent.putExtra(FileDialog.LOADSAVE, "LOAD");
			fileIntent.putExtra(FileDialog.PATHONLY, "false");
			//fileIntent.putExtra("USER_DATA", "loadgpx");
    		startActivityForResult(fileIntent, REQUEST_LOAD_GPX);
    		break;
    		
		case R.id.loadtemp:
    		Intent fileIntent1 = new Intent(terraDroid.this, FileDialog.class);
			fileIntent1.putExtra(FileDialog.START_PATH, "/sdcard");
			fileIntent1.putExtra(FileDialog.LOADSAVE, "LOAD");
			fileIntent1.putExtra(FileDialog.PATHONLY, "false");
			//fileIntent1.putExtra("USER_DATA", "loadtemp");
    		startActivityForResult(fileIntent1, REQUEST_LOAD_TEMP);
    		break;
    		
		case R.id.cleartemp:
			Globals.TempOverlay = null;
			LoadOverlays();
			break;
			
		case R.id.addwaypoint:
			WaypointDialog wpDialog = new WaypointDialog(this, "temp");
			wpDialog.show();
			break;
			
		case R.id.writetemp:
    		Intent fileIntent11 = new Intent(this, FileDialog.class);
			fileIntent11.putExtra(FileDialog.START_PATH, "/sdcard");
			fileIntent11.putExtra(FileDialog.LOADSAVE, "SAVE");
			//fileIntent11.putExtra("USER_DATA", "savetemp");
    		startActivityForResult(fileIntent11, REQUEST_SAVE_TEMP);
			break;		
			
		};
		
		return true;
	};
	
	public void loadGPX(String file) {

		if( file=="" )
			return;
		
        Drawable drawable = this.getResources().getDrawable(R.drawable.pin);
        Globals.TCOverlay = new MapItemizedOverlay(drawable, this, Globals.mapView);
		myCaches = new MyCacheHandler();
		myCaches.LoadCaches(file, Globals.TCOverlay);
		Log.d("Debug", "Overlay size -> "+Globals.TCOverlay.size());
		LoadOverlays();
		
			double dLatBottom = 90;
			double dLatTop = -90;
			double dLonLeft = 180;
			double dLonRight = -180;
			
			//Log.d("Debug", "Creating drawable for n="+MyXMLHandler.getCachesList().getSize());

			/*if( myCaches.getCachesList().getSize()==0 )
				return;*/
			
			for(int i=0; i<Globals.TCOverlay.size(); i++) {
				TCOverlayItem thisCache = (TCOverlayItem) Globals.TCOverlay.getItem(i);
				
				if( thisCache.getLatitude() < dLatBottom )
					dLatBottom = thisCache.getLatitude();
				
				if( thisCache.getLatitude() > dLatTop )
					dLatTop = thisCache.getLatitude();
				
				if( thisCache.getLongitude() < dLonLeft )
					dLonLeft = thisCache.getLongitude();
				
				if( thisCache.getLongitude() > dLonRight )
					dLonRight = thisCache.getLongitude();
			}
	        
			/*
			mapOverlays.clear(); 
			mapOverlays.add(itemizedoverlay);
        	*/
			//LoadTempCaches();
			
			if( Globals.bTrackGPS ) {
        		buttonToggleCentering.setAlpha(255);
               Globals.myLocationOverlay.enableMyLocation(); // blue circle is displayed correctly 
        	}
        	else {
        		buttonToggleCentering.setAlpha(128);
        		Globals.myLocationOverlay.disableMyLocation();
        	}
        	
			mapOverlays.add(Globals.myLocationOverlay);
			
			SetRange(dLatBottom, dLonLeft, dLatTop, dLonRight);
        	if( Globals.bTrackGPS )
               Globals.myLocationOverlay.enableMyLocation(); // blue circle is displayed correctly 
        	else
        		Globals.myLocationOverlay.disableMyLocation();

			Globals.SaveFileNow(file);
	}
	
	public void LoadTempCaches(String filePath) {
		
    	Globals.TempOverlay = new MapItemizedOverlay(Globals.drawableRedPin, this, Globals.mapView);
    	MyCacheHandler myCaches = new MyCacheHandler();
    	myCaches.LoadCaches(filePath, Globals.TempOverlay);
    	Log.d("Debug", "Overlay size -> "+Globals.TempOverlay.size());
    	LoadOverlays();
	}
	
	public void LoadOverlays() {
    	Globals.mapView.getOverlays().clear();
		if (Globals.TCOverlay!=null )
			mapOverlays.add(Globals.TCOverlay);
		if( Globals.TempOverlay!=null )
			mapOverlays.add(Globals.TempOverlay);
    	Globals.mapView.getOverlays().add(Globals.myLocationOverlay);
	}
	
    public synchronized void onActivityResult(final int requestCode, int resultCode, final Intent data) {
    	
            if (resultCode == Activity.RESULT_OK) {
            	String filePath = data.getStringExtra(FileDialog.RESULT_PATH);
            	switch(resultCode) {
            	case REQUEST_LOAD_GPX:
            		loadGPX(filePath);
            		break;
            		
            	case REQUEST_LOAD_TEMP:
            		LoadTempCaches(filePath);
            		break;
            		
            	case REQUEST_SAVE_TEMP:
            		Globals.WriteGPX(filePath);  
            		break;
            		
            	default:
            			break;
            	}
                /*if (requestCode == REQUEST_SAVE) {
                        Log.v("FD", "Saving...");
                        if( data.getStringExtra("USER_DATA").equals("savegpx") )
                        	Globals.WriteGPX(filePath);                        
                        
                } else if (requestCode == REQUEST_LOAD) {
                	//Log.v("FD", "Loading...");
                    
                    Log.v("FD", "File "+filePath+" user data ->"+data.getStringExtra("USER_DATA"));
                    if( data.getStringExtra("USER_DATA").equals("loadgpx") )
                    	loadGPX(filePath);                        
                    
                    if( data.getStringExtra("USER_DATA").equals("loadtemp") )
                    	LoadTempCaches(filePath);
                    
                }   */
                    
            } else if (resultCode == Activity.RESULT_CANCELED) {
            	Log.v("FD", "Request cancelled");
            }
    }
 }